//
//  WmcfunctionSelectView.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/14.
//

import UIKit
import YPBedrock

public extension WmcButtonItemType {
    /// 首页底部功能模块
    enum HomeFunctionMode {
        /// 编辑
        case edit

        /// 数钢筋
        case rebarCount

        /// 拍照
        case photo

        /// 视频
        case video
        
        /// 边拍边拼
        case photoAndCombine

        /// 自定义
        /// - Parameters:
        ///   - text: 文字
        ///   - width: 宽度
        ///   - didSelectBlock: 触发回调
        case custom(text: String,
                    width: CGFloat,
                    didSelectBlock: YPBlock.Empty)
        
        var name: String {
            switch self {
            case .edit:
                return "编辑"
            case .rebarCount:
                return "数钢筋"
            case .photo:
                return "照片"
            case .video:
                return "视频"
            case .photoAndCombine:
                return "边拍边拼"
            case let .custom(text, _, _):
                return text
            }
        }
    }
}

// MARK: - 扩展WmcFunctionSelectView + WmcLifeCycleProtocol

extension WmcFunctionSelectView: WmcLifeCycleProtocol {
    /// 视图即将出现
    func viewWillAppear(_ vc: WmcBaseVC) {
        guard let _ = vc as? WmcHomeVC else { return }
        correction()
    }
}

// MARK: - [WmcFunctionSelectView]

class WmcFunctionSelectView: UICollectionView {
    // Lifecycle

    convenience init() {
        let frame = CGRect(x: 0, y: 0, width: Wmc_screenWidth, height: 30)
        self.init(frame: frame, collectionViewLayout: Self.layout)
        config()
        makeUI()
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // Internal

    static var layout: UICollectionViewFlowLayout {
        let layout = UICollectionViewFlowLayout
            .YP.CreateGridLayout(scrollDirection: .horizontal,
                                 minimumLineSpacing: 0,
                                 minimumInteritemSpacing: 0)
        return layout
    }

    var currentSelectIndex: Int = 0

    /// 点击编辑
    var clickEditBlock: YPBlock.Empty?
    /// 点击数钢筋
    var clickRebarCountBlock: YPBlock.Empty?
    /// 点击照片
    var clickPhotoBlock: YPBlock.Empty?
    /// 点击视频
    var clickVideoBlock: YPBlock.Empty?
    /// 点击边拍边拼
    var clickPhotoAndCombineBlock: YPBlock.Empty?

    /// 背景是否透明状态
    var isTransparent: Bool = false

    var list: [WmcFunctionSelectCell.Model] = []

    var homeDelegate: WmcHomeDelegate? {
        return YPWmcManager.shared.uiDelegate.homeDelegate
    }

    /// 刷新模块
    func reloadItems() {
        reloadData()
    }

    func config() {
        delegate = self
        dataSource = self
        self.yp.registerCells([
            YPRegister(WmcFunctionSelectCell.self),
        ])
        backgroundColor = .clear
        WmcNotice.Register(WmcLifeCycleProtocol.self, observer: self)
        showsVerticalScrollIndicator = false
        showsHorizontalScrollIndicator = false
        isScrollEnabled = false
    }

    func makeUI() {
        list = toItemList(caseList: caseList())
        // 功能少于1个隐藏
        // 不使用 isHidden = list.count <= 1
        if list.count <= 1 { // 为了方便阅读理解，展开书写
            isHidden = true
        } else {
            isHidden = false
        }
    }

    /// 第一个可选的功能模块
    func firstSelectFunction() -> WmcButtonItemType.HomeFunctionMode? {
        let caseList = caseList()
        for (index, model) in list.enumerated() {
            if model.title == "照片" {
                if let cas = caseList.yp.object(at: index) {
                    return cas
                }
            }
        }
        return nil
    }

    /// 选中一个
    func selectIdx(_ index: Int) {
        currentSelectIndex = index
        collectionView(self, didSelectItemAt: .init(item: index, section: 0))
    }

    /// 滑动到选中的
    func correction() {
        // 滑动到选中的item
        scrollToItem(at: .init(item: currentSelectIndex, section: 0),
                     at: .centeredHorizontally, animated: true)
    }

    /// 选中到第一个功能模块。不会出发回调
    func selectFirstAction() {
        // 设置功能模块选中
        for (index, model) in list.enumerated() {
            if model.title == "照片" {
                selectIdx(index)
                break
            }
        }
    }

    func caseList() -> [WmcButtonItemType.HomeFunctionMode] {
        var defaultList: [WmcButtonItemType.HomeFunctionMode] = [
            .edit, .video, .photo, .photoAndCombine
        ]
        if let caseList = homeDelegate?.bottomFunctionList(.current, defaultList: defaultList) {
            defaultList = caseList
        }
        return defaultList
    }

    func toItemList(caseList: [WmcButtonItemType.HomeFunctionMode]) -> [WmcFunctionSelectCell.Model] {
        var items: [WmcFunctionSelectCell.Model] = []
        caseList.forEach { cas in
            switch cas {
            // 编辑
            case .edit:
                let model: WmcFunctionSelectCell.Model =
                    .init(title: "编辑", isUseSelect: false) { [weak self] model in
                        guard let weakSelf = self else { return }
                        weakSelf.clickEditBlock?()
                        YPWmcManager.shared.uiDelegate.homeDelegate?.cameraDidSelectFunctionMode(.current, functionMode: cas)
                    }
                items.append(model)

            // 数钢筋
            case .rebarCount:
                let model: WmcFunctionSelectCell.Model =
                    .init(title: "数钢筋", isUseSelect: true) { [weak self] model in
                        guard let weakSelf = self else { return }
                        weakSelf.clickRebarCountBlock?()
                        YPWmcManager.shared.uiDelegate.homeDelegate?.cameraDidSelectFunctionMode(.current, functionMode: cas)
                    }
                items.append(model)

            // 照片
            case .photo:
                let model: WmcFunctionSelectCell.Model =
                    .init(title: "照片", isUseSelect: true) { [weak self] model in
                        guard let weakSelf = self else { return }
                        weakSelf.clickPhotoBlock?()
                        YPWmcManager.shared.uiDelegate.homeDelegate?.cameraDidSelectFunctionMode(.current, functionMode: cas)
                    }
                items.append(model)

            // 视频
            case .video:
                let model: WmcFunctionSelectCell.Model =
                    .init(title: "视频", isUseSelect: true) { [weak self] model in
                        guard let weakSelf = self else { return }
                        weakSelf.clickVideoBlock?()
                        YPWmcManager.shared.uiDelegate.homeDelegate?.cameraDidSelectFunctionMode(.current, functionMode: cas)
                    }
                items.append(model)
            // 边拍边拼
            case .photoAndCombine:
                let model: WmcFunctionSelectCell.Model =
                    .init(title: "边拍边拼", width: 55.0, isUseSelect: true) { [weak self] model in
                        guard let weakSelf = self else { return }
                        weakSelf.clickPhotoAndCombineBlock?()
                        YPWmcManager.shared.uiDelegate.homeDelegate?.cameraDidSelectFunctionMode(.current, functionMode: cas)
                    }
                items.append(model)

            // 自定义
            case let .custom(text: text, width: width, didSelectBlock: didSelectBlock):
                let model: WmcFunctionSelectCell.Model =
                    .init(title: text, width: width, isUseSelect: false) { model in
                        didSelectBlock()
                        YPWmcManager.shared.uiDelegate.homeDelegate?.cameraDidSelectFunctionMode(.current, functionMode: cas)
                    }
                items.append(model)
            }
        }
        return items
    }
}

// MARK: - UICollectionViewDelegate

extension WmcFunctionSelectView: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let selectModel = list.yp.object(at: indexPath.row) else { return }
        // 该点击是否需要状态
        if selectModel.isUseSelect {
            YPDevice.PlayShake(.light)
            for (idx, model) in list.enumerated() {
                model.isSelect = (idx == indexPath.row)
            }
            collectionView.reloadData()
            // 滑动到选中的item
            currentSelectIndex = indexPath.row
            correction()
        }
        // 事件回调
        selectModel.didSelectBlock?(selectModel)
    }
}

// MARK: - UICollectionViewDelegateFlowLayout

extension WmcFunctionSelectView: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        var width: CGFloat = 35
        if let model = list.yp.object(at: indexPath.row) {
            width = model.width
        }
        width += 12
        return CGSize(width: width, height: collectionView.frame.size.height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        let firstItemWidth = self.collectionView(collectionView,
                                                 layout: collectionViewLayout,
                                                 sizeForItemAt: .init(item: 0, section: section)).width
        let left = (Wmc_screenWidth / 2) - (firstItemWidth / 2)
        let lastItemWidth = self.collectionView(collectionView,
                                                layout: collectionViewLayout,
                                                sizeForItemAt: .init(item: list.count - 1, section: section)).width
        let right = (Wmc_screenWidth / 2) - (lastItemWidth / 2)
        return .init(top: 0, left: left, bottom: 0, right: right)
    }
}

// MARK: - UICollectionViewDataSource

extension WmcFunctionSelectView: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return list.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: WmcFunctionSelectCell = collectionView.yp.dequeueReusableCell(for: indexPath)
        cell.isTransparent = isTransparent
        if let model = list.yp.object(at: indexPath.row) {
            cell.configModel(model)
        }
        return cell
    }
}
